package main.java.com.negromotad.genetics.rules;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.nfunk.jep.JEP;
import org.nfunk.jep.ParseException;

public class TMJepRule implements TMRule {

	private String expression;
	private JEP parser;

	public TMJepRule(String expression) {
		parser = new JEP();
		if (expression.isEmpty()) {
			System.out.println("WARNING: Empty expression rule");
		}
		this.expression = expression;
	}

	public boolean evaluate(Map<String, Integer> map) {

		for (Entry<String, Integer> entry : map.entrySet()) {
			parser.addVariable(entry.getKey(), entry.getValue());
		}
		parser.parseExpression(this.expression);
		int aux;
		try {
			aux = ((Double) parser.evaluate(parser.getTopNode())).intValue();
		} catch (ParseException e) {
			return false;
		}
		if (aux == 1) {
			return true;
		}
		return false;
	}

	public boolean checkExpression(List<String> list) {
		JEP parser = new JEP();
		for (String string : list) {
			parser.addVariable(string, "0");
		}

		parser.parseExpression(this.expression);
		if (parser.hasError())
			return false;
		return true;
	}
}
